package cn.zhz.cloud.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import cn.zhz.cloud.token.dto.CurrentUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import static cn.zhz.cloud.token.constant.TokenConstant.*;


/**
 * 包装用户信息下发到资源服务
 * 之所以使用WebFilter没使用GlobalFilter因为会出现用户信息错乱问题，
 * 可能和线程池共享变量有款，后期再排查
 */
@Slf4j
@Order(1)
@Component
public class CurrentUserWebFilter implements WebFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        CurrentUserDto currentUserDto;
        if (StpUtil.isLogin()) {
            currentUserDto = StpUtil.getTokenSession().getModel(SA_MODEL_KEY_USER, CurrentUserDto.class);
        } else {
            currentUserDto = ANONYMOUS_USER_DTO;
        }
        String userInfo = JSONUtil.toJsonStr(currentUserDto, new JSONConfig().setIgnoreNullValue(false));
        mutate.header(HEADER_USER, SecureUtil.aes(TOKEN_AES_CRYPTO_KEY_BYTE).encryptBase64(userInfo));

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

}
